package org.nextive.android.weightapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class ContactManager extends Activity 
{
	//Constant for extra key email
	public static String EXTRA_KEY_EMAIL = "email";
	
	private ListView listViewContacts;
	private Button buttonAddContact;
	
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contact_manager);
		
		listViewContacts = (ListView) findViewById(R.id.listViewContacts);
		listViewContacts.setOnItemClickListener(new OnItemClickListener() 
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,long id) 
			{
				pickContact(id);
			}
		});
		
		buttonAddContact = (Button) findViewById(R.id.buttonAddContact);
		buttonAddContact.setOnClickListener(new OnClickListener() 
		{	
			@Override
			public void onClick(View v) 
			{
				Intent addContactIntent = new Intent(ContactManager.this, AddContact.class);
				startActivity(addContactIntent);
			}
		});
		
		fillData();
    }
	
	private void fillData()
	{
		Uri uri = ContactsContract.Contacts.CONTENT_URI;
        String[] projection = new String[] {ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME};
        
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

        Cursor cursor = managedQuery(uri, projection, null, null, sortOrder);
        
        String[] fields = new String[] {ContactsContract.Data.DISPLAY_NAME};
        
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_row, cursor,
                fields, new int[] {R.id.textViewContactName});
        
        listViewContacts.setAdapter(adapter);
	}
	
	private void pickContact(long id)
	{
		String contactId = String.valueOf(id);
		Cursor cursorEmail = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
    			null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{contactId}, null);
		
		if (cursorEmail.getCount()>0)
		{
			final String[] emails;
			try
			{
				emails = new String[cursorEmail.getCount()];
				while(cursorEmail.moveToNext())
				{
					emails[cursorEmail.getPosition()] = cursorEmail.getString(cursorEmail.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));	
				}
			}
			finally
			{
				cursorEmail.close();
			}
			
			AlertDialog.Builder builder = new AlertDialog.Builder(ContactManager.this);
	        builder.setTitle(R.string.select_email);
	        builder.setItems(emails, new DialogInterface.OnClickListener() 
	        {
	            public void onClick(DialogInterface dialog, int item) 
	            {
	            	Intent starterIntent = ContactManager.this.getIntent();
	            	starterIntent.putExtra(EXTRA_KEY_EMAIL, emails[item]);
	            	ContactManager.this.setResult(RESULT_OK, starterIntent);
	            	ContactManager.this.finish();
	            }
	        });
	        AlertDialog alert = builder.create();
	        alert.show();
		}
		else
		{
			Toast.makeText(getApplicationContext(), R.string.contact_does_not_have_email, Toast.LENGTH_SHORT).show();
		}
	}
}
